package net.loodies;




import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Enumeration;
import java.util.Hashtable;


import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;


public class Utils {

	 private static final boolean DEBUG = false;
	 protected static final String TAG = "Utils";
	 public static boolean ASSERT_AND_ERROR(boolean value,
			 		String error,
			 		LoodiesErrorListener loodiesErrorCallback){
		 if(!value){
				if(loodiesErrorCallback!=null){
					 loodiesErrorCallback.notifyError(LoodiesErrorListener.ERROR_CONSTRUCTOR,error);
					
				 }
				 return false;
			}
		 return true;
	 }
		
	 static int getHigherPow2(int x){
		 if (x == 0)
			 return 0;

			 x--;
			 x = (x >> 1) | x;
			 x = (x >> 2) | x;
			 x = (x >> 4) | x;
			 x = (x >> 8) | x;
			 x = (x >> 16) | x;
			 x++;
			 return x;
	 }
	 
	
	public static String loadJSON(String fileUrl) {
		URL myFileUrl = null;
		String result = "";
		try {
			myFileUrl = new URL(fileUrl);
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			URLConnection urlConn = null;
			urlConn = myFileUrl.openConnection();
			InputStream result2 = urlConn.getInputStream();
			result = result2.toString();

			HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
			
			conn.connect();
			InputStream is = conn.getInputStream();
			result = ReadInputStream(is);
			

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
	}

	static public String ReadInputStream(InputStream in) throws IOException {
		StringBuffer stream = new StringBuffer();
		byte[] b = new byte[4096];
		for (int n; (n = in.read(b)) != -1;) {
			stream.append(new String(b, 0, n));
		}
		return stream.toString();
	}

	static public Bitmap downloadFile(String bitmapUrlStr) {
		URL bitmapUrl = null;
		try {
			bitmapUrl = new URL(bitmapUrlStr);
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		HttpGet httpRequest = null;

		try {
			httpRequest = new HttpGet(bitmapUrl.toURI());
		} catch (URISyntaxException e) {
			e.printStackTrace();
		}

		HttpClient httpclient = new DefaultHttpClient();
		HttpResponse response = null;
		try {
			response = (HttpResponse) httpclient.execute(httpRequest);
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}

		HttpEntity entity = response.getEntity();
		BufferedHttpEntity bufHttpEntity = null;
		try {
			bufHttpEntity = new BufferedHttpEntity(entity);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			InputStream instream = bufHttpEntity.getContent();
			Bitmap _bitmap = BitmapFactory.decodeStream(instream);
			return _bitmap;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	public static Hashtable<String, String> parse(String jString) throws Exception {
		JSONObject jObject = new JSONObject(jString);
		String nbad = jObject.getString("nb_ads");
		Hashtable<String, String> map = new Hashtable<String, String>();
		int inbad = Integer.parseInt(nbad);
		if (inbad < 1) {
			if (DEBUG) {
				//System.out.println("error bad JSon file");
			}	
			return map;
		}

		JSONObject slotObject = jObject.getJSONObject("slot");
		JSONArray resourcesArray = jObject.getJSONArray("resources");
		JSONArray resultsArray = jObject.getJSONArray("results");

		map.put("nb_ads", jObject.getString("nb_ads"));
		

		map.put("method", jObject.getString("method"));
		map.put("position", slotObject.getString("position"));
		map.put("click_notification_url", slotObject
				.getString("click_notification_url"));
		map.put("height", slotObject.getString("height"));
		map.put("width", slotObject.getString("width"));
		map.put("type", slotObject.getString("type"));

		map.put("ad_destination_url", resultsArray.getJSONObject(0).getString(
				"ad_destination_url").toString());
		map.put("ad_format", resultsArray.getJSONObject(0).getString(
				"ad_format").toString());
		map.put("ad_html", resultsArray.getJSONObject(0).getString("ad_html")
				.toString());
		map.put("ad_contextual_content", resultsArray.getJSONObject(0)
				.getString("ad_contextual_content").toString());
		map.put("ad_object_type", resultsArray.getJSONObject(0).getString(
				"ad_object_type").toString());
		map.put("ad_type", resultsArray.getJSONObject(0).getString("ad_type")
				.toString());
		map.put("ad_object_url", resultsArray.getJSONObject(0).getString(
				"ad_object_url").toString());

		if (resourcesArray.length() > 0) {
			map.put("ad_resource_index", resultsArray.getJSONObject(0)
					.getString("ad_resource_index").toString());

			map.put("container_height", resourcesArray.getJSONObject(0)
					.getString("container_height").toString());
			map.put("container_width", resourcesArray.getJSONObject(0)
					.getString("container_width").toString());
			map.put("container_url", resourcesArray.getJSONObject(0).getString(
					"container_url").toString());
			map.put("close_url", resourcesArray.getJSONObject(0).getString(
					"close_url").toString());

		}
		
		Enumeration<String> e = map.keys();

		while (e.hasMoreElements() == true) {
			String key = (String) e.nextElement();
			String value = map.get(key);
			// do whatever you need with the pair, like
			if (DEBUG) {
				System.out.println("'" + key + "' associated with '" + value + "'");
			}	//
		}

		return map;
	}
	
	  public static void GotoAdvitiser(Activity parentActivity,String urlDestination,String urlNotification){
			
		    if(parentActivity==null){
		    	return;
		    }
		    
		    String notify = urlNotification;
			String destination = urlDestination;
			Manager.Stop();

			URL myFileUrl = null;
			try {
				myFileUrl = new URL(notify);
			} catch (MalformedURLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			HttpURLConnection conn = null;
			try {
				conn = (HttpURLConnection) myFileUrl.openConnection();
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			
			try {
				conn.connect();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			try {
				@SuppressWarnings("unused")
				InputStream is = conn.getInputStream();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if (AccelerometerManager.isListening()) {
	    		AccelerometerManager.stopListening();
	    	}
		   	Intent i = new Intent(Intent.  ACTION_VIEW);
			i.setData(Uri.parse(destination));
			parentActivity.startActivity(i);
			
	}
}
